﻿using System;
using System.Collections.Generic;

using WAF.EntityFramework;
using TradeClient.Logic.Entity;

namespace TradeClient.Logic.TradeCore
{
    /// <summary>
    /// 交易管理类
    /// </summary>
    public class TradeManager
    {
        /// <summary>
        /// 单例模式实例对象
        /// </summary>
        private static TradeManager instance;

        /// <summary>
        /// 软件启动以后是否更新过合约信息
        /// </summary>
        public bool IsUpdateInstrument = false;


        /******************************** Public ********************************/

        /// <summary>
        /// 取得交易管理类实例
        /// </summary>
        /// <returns>交易管理类实例</returns>
        public static TradeManager GetInstance()
        {
            if (instance == null)
                instance = new TradeManager();

            return instance;
        }

        /// <summary>
        /// 交易
        /// </summary>
        /// <param name="ctpOrder">交易账单</param>
        public void Trade(CtpOrder ctpOrder)
        {
            //平仓使用相反交易方向
            if (ctpOrder.OpenClose == OpenCloseType.Close)
            {
                if (ctpOrder.Direction == DirectionType.Buy)
                    ctpOrder.Direction = DirectionType.Sell;
                else
                    ctpOrder.Direction = DirectionType.Buy;
            }

            RecordTrade(ctpOrder);

            CtpTrade ctpTrade = ctpOrder.AccountObject.CtpTradeObject;
            ctpTrade.OrderInsert(ctpOrder);

            System.Media.SystemSounds.Beep.Play();
        }


        /******************************** private ********************************/

        /// <summary>
        /// 私有构造函数，防止显示实例化
        /// </summary>
        private TradeManager()
        {

        }

        /// <summary>
        /// 记录交易
        /// </summary>
        /// <param name="tradeRecord">交易记录</param>
        private void RecordTrade(CtpOrder order)
        {
            //交易记录
            TradeHistory tradeRecord = new TradeHistory();

            tradeRecord.TradeTime   = DateTime.Now.ToString();
            tradeRecord.Policy      = order.Policy;
            tradeRecord.Market      = order.Market.ToString();
            tradeRecord.Account     = order.Account;
            tradeRecord.Code        = order.Code;
            tradeRecord.Level       = order.Level.ToString();
            tradeRecord.Unit        = order.Unit.ToString();
            tradeRecord.Direction   = order.Direction.ToString();
            tradeRecord.OpenClose   = order.OpenClose.ToString();
            tradeRecord.Volume      = order.Volume;
            tradeRecord.Price       = order.Price;

            EntityAction.Insert(tradeRecord);
        }
    }
}
